<template>
  <div class="app-container">
    <div class="filter-container">
      <el-cascader
          v-if="level == 1"
          class="filter-item"
          v-model="selectParent" :options="distributorsList"
          :props="distributorsProps"
          placeholder="所属经销商"
          @change="getList"
          style="width: 15%" clearable filterable></el-cascader>

      <el-select v-model="listQuery.status" filterable placeholder="订单状态" class="filter-item" clearable
                 @change="getList" style="width: 10%;margin-left: 10px;"
      >
        <el-option label="未支付" value="unpaid"></el-option>
        <el-option label="已支付" value="paid"></el-option>
        <el-option label="使用中" value="using"></el-option>
        <el-option label="已结束" value="end"></el-option>
        <el-option label="失败" value="failed"></el-option>
        <el-option label="已退款" value="refunded"></el-option>
        <el-option label="支付超时" value="timeout"></el-option>
      </el-select>
      <el-input
          class="filter-item"
          placeholder="输入订单号"
          v-model="listQuery.keyword"
          style="margin-left:5px;width: 10%"
          @keyup.enter.native="getList"
      >
      </el-input>
      <el-input
          class="filter-item"
          placeholder="回执单号"
          v-model="listQuery.out_ord_id"
          style="margin-left:5px;width: 10%"
          @keyup.enter.native="getList"
      >
      </el-input>
      <el-input
          class="filter-item"
          placeholder="站点地址"
          v-model="listQuery.address"
          style="width: 10%;margin-left:5px;"
          @keyup.enter.native="getList"
      >
      </el-input>

      <el-input
          class="filter-item"
          placeholder="设备编号"
          v-model="listQuery.sn"
          style="width: 10%;margin-left:5px;"
          @keyup.enter.native="getList"
      >
      </el-input>

      <el-input
          class="filter-item"
          placeholder="端口号"
          v-model="listQuery.channel_number"
          style="width: 10%;margin-left:5px;"
          @keyup.enter.native="getList"
      >
      </el-input>
      <el-radio-group v-model="listQuery.payment_type" @change="getList"
                      fill="#67C23A"
                      class="filter-item" style="margin-left: 15px"
      >
        <el-radio-button label="">全部</el-radio-button>
        <el-radio-button label="balance">余额</el-radio-button>
        <el-radio-button label="wx_lite">微信</el-radio-button>
        <el-radio-button label="alipay_lite">支付宝</el-radio-button>
      </el-radio-group>
      <!--      <el-button class="filter-item" type="success" style="float:right;margin-right:10px" @click="handleClickExport">-->
      <!--        导出关键词-->
      <!--      </el-button>-->
      <el-divider style="margin-top:-10px"></el-divider>
      <div class="filter-container">
        <el-input
            class="filter-item"
            placeholder="功率范围/W(小)"
            v-model="listQuery.min_power"
            style="margin-left:5px;width: 10%"
            @keyup.enter.native="getList"
        >
        </el-input>
        <el-input
            class="filter-item"
            placeholder="功率范围/W(大)"
            v-model="listQuery.max_power"
            style="margin-left:5px;width: 10%"
            @keyup.enter.native="getList"
        >
        </el-input>

        <el-date-picker
            class="filter-item"
            style="margin-left:10px;"
            v-model="listQuery.time"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="getList"
            align="right"
        >
        </el-date-picker>
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getList"
                   style="margin-left: 5px"
        >
          搜索
        </el-button>
        <!--      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"-->
        <!--                 @click="handleDownload"-->
        <!--      >-->
        <!--        导出-->
        <!--      </el-button>-->
        <!--      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">-->
        <!--        审核-->
        <!--      </el-checkbox>-->
      </div>
      <el-card>

        <el-checkbox-group v-model="checkedIds" @change="handleCheckedIdsChange">
          <el-table v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%">
            <el-table-column align="center" label="ID" min-width="80">
              <template slot-scope="scope">
                <el-checkbox :key="scope.row.id" :label="scope.row.id"
                ></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column min-width="80" align="center" label="站点" v-if="listQuery.type_id != 8">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" :content="scope.row.address" placement="top-start">
                  <el-link type="success">{{ scope.row.station_name }}</el-link>
                </el-tooltip>
                <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
              </template>
            </el-table-column>
            <el-table-column min-width="80" align="center" label="订单号">
              <template slot-scope="scope">
                <span>{{ scope.row.number }}</span>
                <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
              </template>
            </el-table-column>
            <el-table-column min-width="80" align="center" label="设备/端口">
              <template slot-scope="scope">
                <span>{{ scope.row.sn }}-{{ scope.row.channel_number }}</span>
                <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
              </template>
            </el-table-column>
            <el-table-column min-width="70" align="center" label="用户">
              <template slot-scope="scope">
                <span>{{ scope.row.nickname }}</span>
                <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
              </template>
            </el-table-column>
<!--            <el-table-column min-width="80" align="center" label="预计时长">-->
<!--              <template slot-scope="scope">-->
<!--                <span v-if="scope.row.use_elec > 0">已使用{{ (scope.row.use_elec / 1000).toFixed(2) }}度</span>-->
<!--                <span v-else>{{ scope.row.minutes | formatMinutes }}</span>-->
<!--                &lt;!&ndash;          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>&ndash;&gt;-->
<!--              </template>-->
<!--            </el-table-column>-->
            <el-table-column min-width="80" align="center" label="自停">
              <template slot-scope="scope">
                <span v-if="scope.row.is_autoload > 0">是</span>
                <span v-else>否</span>
                <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
              </template>
            </el-table-column>
<!--            <el-table-column min-width="100" align="center" label="功率检测">-->
<!--              <template slot-scope="scope">-->
<!--                <span v-if="scope.row.is_check == 1">已检测(功率计费)</span>-->
<!--                <span v-else-if="scope.row.is_check == 2">无需检测</span>-->
<!--                <span v-else>未检测</span>-->
<!--                &lt;!&ndash;          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>&ndash;&gt;-->
<!--              </template>-->
<!--            </el-table-column>-->
            <el-table-column min-width="80" align="center" label="充电时长">
              <template slot-scope="scope">
                <span>{{ scope.row.duration_seconds | formatSecond }}</span>
                <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
              </template>
            </el-table-column>
            <el-table-column min-width="50" align="center" label="支付金额">
              <template slot-scope="scope">
                <span>{{ scope.row.fee }}</span>
                <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
              </template>
            </el-table-column>
            <el-table-column min-width="50" align="center" label="消费金额">
              <template slot-scope="scope">
  <span>
    {{
      (scope.row.power_fee && scope.row.return_fee && scope.row.pre_fee) ?
          ((+scope.row.power_fee >= 0 && +scope.row.return_fee >= 0 && +scope.row.pre_fee >= 0) ?
              ((+scope.row.power_fee - +scope.row.return_fee).toFixed(2) > 0 ?
                  (+scope.row.power_fee - +scope.row.return_fee).toFixed(2) : 0.00)
              : 0.00)
          : 0.00
    }}
  </span>
                <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
              </template>
            </el-table-column>
            <el-table-column min-width="50" align="center" label="充电原价">
              <template slot-scope="scope">
                <span>{{ scope.row.original_fee }}</span>
                <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
              </template>
            </el-table-column>
            <el-table-column min-width="50" align="center" label="抵扣金额">
              <template slot-scope="scope">
                <span>{{ scope.row.original_fee - scope.row.power_fee }}</span>
                <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
              </template>
            </el-table-column>
            <el-table-column min-width="70" align="center" label="退款金额">
              <template slot-scope="scope">
                <span v-if="scope.row.is_return_fee">{{ scope.row.return_fee }}已退款</span>
                <span v-else>{{ scope.row.return_fee }}未退款</span>
                <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
              </template>
            </el-table-column>
            <el-table-column min-width="100" align="center" label="已用金额">
              <template slot-scope="scope">
                <span>服务{{ scope.row.charge_service }}元
                电费{{ scope.row.use_fee}}元</span>
                <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
              </template>
            </el-table-column>
            <el-table-column min-width="80" align="center" label="保障服务">
              <template slot-scope="scope">
                <el-tag type="success" v-if="scope.row.service_id && scope.row.service_fee >0">
                  {{ scope.row.service_name }}/{{ scope.row.service_fee }}
                </el-tag>
                <el-tag type="info" v-else-if="scope.row.service_id && scope.row.service_fee <=0">
                  {{ scope.row.service_name }}/已退
                </el-tag>
                <el-tag type="info" v-else>无</el-tag>
                <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
              </template>
            </el-table-column>
            <el-table-column min-width="80" align="center" label="订单套餐">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="showCharge(scope.row.charge_id)">查看</el-button>
              </template>
            </el-table-column>
            <!--            <el-table-column min-width="120" align="center" label="经销商分成">-->
            <!--              <template slot-scope="scope">-->
            <!--                <span v-if="scope.row.distributor_history.length > 0">-->
            <!--                 <el-link-->
            <!--                     v-for="item in scope.row.distributor_history">{{-->
            <!--                     '[' + item.level + '级]' + item.name + '分成' + item.fee-->
            <!--                   }}</el-link>-->
            <!--                </span>-->
            <!--                <el-link v-else>无</el-link>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <el-table-column min-width="60" align="center" label="状态">
              <template slot-scope="scope">
                <span v-if="scope.row.status == 'unpaid'">未支付</span>
                <span v-else-if="scope.row.status == 'paid'">已支付</span>
                <span v-else-if="scope.row.status == 'using'">使用中</span>
                <span v-else-if="scope.row.status == 'end'">已结束</span>
                <span v-else-if="scope.row.status == 'failed'">失败</span>
                <span v-else-if="scope.row.status == 'refunded'">已退款</span>
                <span v-else>支付超时</span>
                <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
              </template>
            </el-table-column>
            <el-table-column min-width="65" align="center" label="分润状态">
              <template slot-scope="scope">
                <el-link type="primary" v-if="scope.row.is_draw == 1">异常</el-link>
                <el-link type="success" v-else>正常</el-link>
                <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
              </template>
            </el-table-column>
            <el-table-column min-width="60" align="center" label="功率">
              <template slot-scope="scope">
                <span>{{ scope.row.power }}W</span>
                <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
              </template>
            </el-table-column>
            <el-table-column min-width="60" align="center" label="用电量">
              <template slot-scope="scope">
                <span v-if="scope.row.use_elec">{{ (scope.row.use_elec/1000).toFixed(2) }}度</span>
                <span v-else>0度</span>
                <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
              </template>
            </el-table-column>
            <el-table-column min-width="70" align="center" label="开始时间">
              <template slot-scope="scope">
                <span>{{ scope.row.estimate_stop_at }}</span>
                <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
              </template>
            </el-table-column>
            <el-table-column min-width="70" align="center" label="结束时间">
              <template slot-scope="scope">
                <span>{{ scope.row.stop_at }}</span>
                <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
              </template>
            </el-table-column>
            <el-table-column min-width="80" align="center" label="停止原因">
              <template slot-scope="scope">
                <span>{{ scope.row.stop_reason }}</span>
              </template>
            </el-table-column>
            <el-table-column min-width="60" align="center" label="支付类型">
              <template slot-scope="scope">
                <el-link type="success" v-if="scope.row.payment_type == 'wx_lite'">微信</el-link>
                <el-link type="primary" v-else-if="scope.row.payment_type == 'alipay_lite'">支付宝</el-link>
                <el-link type="info" v-else>余额</el-link>
                <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
              </template>
            </el-table-column>
            <el-table-column min-width="80" align="center" label="回执单号">
              <template slot-scope="scope">
                <span>{{ scope.row.out_ord_id }}</span>
                <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
              </template>
            </el-table-column>
            <el-table-column
                align="center"
                fixed="right"
                label="操作"
                width="60"
            >
              <template slot-scope="scope">
                <el-dropdown @command="handleCommand" type="primary">
               <span class="el-dropdown-link">
    <i class="el-icon-arrow-down el-icon--right"></i>
  </span>
                  <el-dropdown-menu slot="dropdown">
<!--                    <el-dropdown-item v-if="scope.row.is_draw == 1" :command="{'row': scope.row, 'type': 'draw'}">手动分润-->
<!--                    </el-dropdown-item>-->
                    <el-dropdown-item :command="{'row': scope.row, 'type': 'stop'}">结束订单</el-dropdown-item>
<!--                    <el-dropdown-item :command="{'row': scope.row, 'type': 'refund'}">退款安心充</el-dropdown-item>-->
                    <el-dropdown-item :command="{'row': scope.row, 'type': 'refundNormal'}">自定义退款
                    </el-dropdown-item>
                    <!--                    <el-dropdown-item :command="{'row': scope.row, 'type': 'updateParams'}">修改配置</el-dropdown-item>-->
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
        </el-checkbox-group>
        <el-divider>
          <el-checkbox :indeterminate="isIndeterminate" style="margin-left:10px;" v-model="checkAll"
                       @change="handleCheckAllChange"
          >全选
          </el-checkbox>
          <!--          <el-button type="primary" size="mini" round style="margin-left:10px;" @click="batchOcpc">批量回传</el-button>-->
        </el-divider>
      </el-card>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                  @pagination="getList"
      />

      <el-dialog :title="'套餐名称：'+now_charge.name" :visible.sync="showChargeVisible" width="50%">
        <el-descriptions title="套餐信息" border>
          <el-descriptions-item label="套餐类型" v-if="now_charge.type == 3">电量套餐</el-descriptions-item>
          <el-descriptions-item label="套餐类型" v-else>常规套餐</el-descriptions-item>
          <el-descriptions-item label="充满自停">{{ now_charge.is_autoload == 1 ? '开' : '关' }}</el-descriptions-item>
          <el-descriptions-item label="充满自停金额">{{ now_charge.fee }}</el-descriptions-item>
          <el-descriptions-item label="最低消费金额">{{ now_charge.pre_fee }}/元</el-descriptions-item>
          <el-descriptions-item label="服务单价" v-if="now_charge.type == 3">{{ now_charge.service_fee }}/元
          </el-descriptions-item>
          <el-descriptions-item label="收取类型" v-if="now_charge.type == 3">
            {{ now_charge.service_type == 1 ? '每度' : '每小时' }}
          </el-descriptions-item>
          <el-descriptions-item label="电价/每度" v-if="now_charge.type == 3">{{ now_charge.elec_price }}元
          </el-descriptions-item>
          <el-descriptions-item label="最大充电量" v-if="now_charge.type == 3">{{ now_charge.elec }}
          </el-descriptions-item>
        </el-descriptions>
        <el-card v-if="now_charge.type != 3">
          <el-divider>功率选项</el-divider>
          <div v-for="item in now_charge.power_children">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="每元分钟数">{{ item.minutes }}</el-descriptions-item>
              <el-descriptions-item label="功率范围/W ">{{ item.min_power }}W至{{
                  item.max_power
                }}W
              </el-descriptions-item>
              <el-descriptions-item label="生效时间">{{ item.created_at }}</el-descriptions-item>
            </el-descriptions>
          </div>
          <el-divider>时间选项</el-divider>
          <div v-for="item in now_charge.time_children">
            <el-descriptions border>
              <el-descriptions-item label="总分钟数">{{ item.minutes }}</el-descriptions-item>
              <el-descriptions-item label="金额">{{ item.fee }}</el-descriptions-item>
              <el-descriptions-item label="生效时间">{{ item.created_at }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
        <el-card v-else>
          <el-divider>电量选项</el-divider>
          <div v-for="item in now_charge.elec_children">
            <el-descriptions border>
              <el-descriptions-item label="金额">{{ item.fee }}</el-descriptions-item>
              <el-descriptions-item label="生效时间">{{ item.created_at }}</el-descriptions-item>
            </el-descriptions>
          </div>
          <el-divider>服务费档位</el-divider>
          <div v-for="item in now_charge.service_children">
            <el-descriptions border>
              <el-descriptions-item label="功率范围/W ">{{ item.min_power }}W至{{ item.max_power }}W</el-descriptions-item>
              <el-descriptions-item label="元/每小时">{{ item.fee }}</el-descriptions-item>
              <el-descriptions-item label="生效时间">{{ item.created_at }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import {getList, stopOrder, cancelDraw, getChart, refundService, refundNormal} from '@/api/order'
import {all, del} from '@/api/distributors'
// import { getMenus } from '@/api/menu'
import Pagination from '@/components/Pagination'
import store from '@/store'
import router from '@/router' // Secondary package based on el-pagination
import ImageCropper from '@/components/ImageCropper'
import PanThumb from '@/components/PanThumb'
import {formatMoney} from '@/api/util'
import {getNewClass} from '@/api/contract_class'
import LineChart from './components/LineChart'
import {chargeDetail} from "@/api/device";

const lineChartData = {
  views: {
    expectedData: [100, 120, 161, 134, 105, 160, 165],
    actualData: [120, 82, 91, 154, 162, 140, 145],
    serviceData: [20, 82, 91, 54, 62, 40, 45]
  }
}
const lineData = {
  week: ['上周一', '上周二', '上周三', '上周四', '上周五', '上周六', '上周日'],
  month: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
}

export default {
  name: 'OrderDevice',
  components: {Pagination, ImageCropper, PanThumb, LineChart},
  filters: {
    moenyFormat(value) {
      if (!value) return ''
      return formatMoney(value)
    },
    formatMinutes(value) {
      const hours = Math.floor(value / 60);
      const minutes = value % 60;
      const seconds = "00";
      return `${hours}小时${minutes.toString().padStart(2, "0")}分${seconds.toString().padStart(2, "0")}秒`;
    },
    formatSecond(value) {
      const hours = Math.floor(value / 3600);
      const minutes = Math.floor((value % 3600) / 60);
      const seconds = value % 60;
      return `${hours}小时${minutes.toString().padStart(2, "0")}分${seconds.toString().padStart(2, "0")}秒`;
    },
  },
  data() {
    return {
      selectParent: '',
      distributorsList: [],
      distributorsProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        checkStrictly: true
      },
      lineChartData: [],
      lineData: [],
      nowBatch: 0,
      checkedIds: [],
      checkAll: false,
      idOptions: [],
      isIndeterminate: true,
      pickerOptions: {
        shortcuts: [{
          text: '最近三天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      todayMoney: '',
      typeList: [],
      imagecropperShow: false,
      imagecropperKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      showChart: 2,
      totalPower: 0,
      totalService: 0,
      totalReturn: 0,
      totalSelf: 0,
      listQuery: {
        page: 1,
        limit: 20,
        distributor_id: [],
        keyword: '',
        time: [],
        status: '',
        min_power: '',
        max_power: '',
        sn: '',
        channel_number: '',
        payment_type: '',
        out_ord_id: '',
        is_drawer: ''

      },
      level:'',
      now_charge: [],
      dialogFormVisible: false,
      dialogStatus: '',
      showChargeVisible: false,
      textMap: {
        update: '编辑',
        create: '创建'
      },
      filterText: '',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      class_id: [],
      timeMoney: '',
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    let distributor_id = this.$route.query.distributor_id
    if (distributor_id) {
      this.selectParent = +distributor_id
    }
    this.setLastWeekAsDefault()
    this.getList()
    this.getSelector()
    this.level = this.$store.getters.introduction
  },
  methods: {
    showCharge(id) {
      this.showChargeVisible = true
      chargeDetail(id).then(response => {
        this.now_charge = response.data
      })
    },
    handleSetLineChartData(type) {
      this.selectType = type
      this.lineChartData = lineChartData[type]
    },
    formatDate(date) {
      const year = date.getFullYear();
      // getMonth 返回的是从 0 开始的月份，因此要加 1
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');

      // 根据需要的格式拼接字符串
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    setLastWeekAsDefault() {
      const end = new Date();
      const start = new Date();
      start.setTime(end.getTime() - 3600 * 1000 * 24 * 3);

      // 直接更新 listQuery.time 属性以设置默认时间范围
      this.listQuery.time = [this.formatDate(start), this.formatDate(end)];
    },
    getChart() {
      if (this.showChart == 1) {
        if (this.listQuery.time.length > 0) {
          getChart(this.listQuery).then(response => {
            this.lineChartData = response.data.list
            this.lineData = response.data.key
            this.totalPower = response.data.total.powerfee.toFixed(2)
            this.totalService = response.data.total.servicefee.toFixed(2)
            this.totalReturn = response.data.total.returnfee.toFixed(2)
            this.totalSelf = response.data.total.selffee.toFixed(2)
          })
        } else {
          this.$message.info('查看折线图数据请先选择时间段');
          this.lineChartData = [];
          this.lineData = [];
          this.totalPower = this.totalService = this.totalReturn = 0;
        }
      }
    },

    handleCommand({row, type}) { // 解构参数对象
      switch (type) {
        case 'stop':
          this.stopOrder(row)
          break
        case 'draw':
          this.cancelDraw(row)
          break;
        case 'refund':
          this.refundService(row)
          break;
        case'refundNormal':
          this.refundNormal(row)
          break;
        default:
          this.stopOrder(row)
          break
      }
    },

    stopOrder(row) {
      if (row.status != 'using' && row.status != 'paid') {
        this.$message.info('只能结束当前正在进行中的订单')
        return ''
      }
      this.$confirm('确认要结束该订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        stopOrder(row.id).then(response => {
          this.$notify.info({
            title: '消息提示',
            message: response.msg,
            offset: 100
          })
          this.getList()
        })
      }).catch(() => {

      })
    },

    refundNormal(row) {
      if (row.status == 'unpaid' || row.status == 'timeout') {
        this.$message.error('该订单并未实际支付金额，无须退款')
        return
      }
      this.$prompt('请输入退款金额，退款总金额不可大于订单支付总额', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: (row.fee - row.return_fee - row.service_fee).toFixed(2)
      }).then(({value}) => {
        // if(value > (row.fee-row.service_fee).toFixed(2)){
        //   this.$message.error('最多退款'+(row.fee-row.service_fee).toFixed(2)+'元,不包含退款安心充金额')
        //   return
        // }
        refundNormal(row.id, value).then(response => {
          if (response.code == 200) {
            this.$notify.success({
              title: '成功',
              message: response.msg,
              type: 'success',
              duration: 2000
            })
            this.getList()
          } else {
            this.$notify.error({
              title: '失败',
              message: response.msg,
              duration: 2000
            })
          }
        })
      });
    },

    refundService(row) {
      if (row.status != 'end' && row.status != 'refunded') {
        this.$message.info('请在订单结束后退款安心充')
      }
      if (row.service_fee <= 0) {
        this.$message.info('当前订单不符合退款安心充条件')
        return ''
      }
      this.$confirm('确认要退款该订单安心充金额吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        refundService(row.id).then(response => {
          this.$notify.info({
            title: '消息提示',
            message: response.msg,
            offset: 100
          })
          this.getList()
        })
      }).catch(() => {

      })
    },
    cancelDraw(row) {
      if (row.is_draw != 1) {
        this.$message.info('该订单未延时 无需取消')
        return ''
      }
      cancelDraw(row.id).then(response => {
        this.$notify.info({
          title: '消息提示',
          message: response.msg,
          offset: 100
        })
      })
      this.getList()
    },
    getSelector() {
      all('all').then(response => {
        this.distributorsList = response.data
      })
    },
    handleCheckedIdsChange(value) {
      let checkedCount = value.length
      this.checkAll = checkedCount === this.idOptions.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.idOptions.length
    },
    handleCheckAllChange(val) {
      this.checkedIds = val ? this.idOptions : []
      this.isIndeterminate = false
    },
    toUrl(contract_id) {
      window.open('https://www.wenhetong.com/contractdetail/' + contract_id + '.html')
    },
    getAccount() {
      getAll().then(response => {
        this.account_list = response.data// Just to simulate the time of the request
      })
    },
    handleClickExport() {
      if (this.listQuery.time.length > 0) {
        let search = JSON.stringify(this.listQuery)
        window.open('/api/excel/export_keyword?search=' + search)
      } else {
        this.$message.info('请先选择下载时间段')
      }
    },
    getList() {
      this.listLoading = true
      if (Array.isArray(this.selectParent)) {
        this.listQuery.distributor_id = this.selectParent[this.selectParent.length - 1];
      } else {
        if (this.selectParent) {
          this.listQuery.distributor_id = this.selectParent
        } else {
          this.listQuery.distributor_id = ''
        }
      }
      getList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
        this.idOptions = []
        this.checkedIds = []
        for (var i in this.list) {
          this.idOptions[i] = this.list[i].id
        }
      })
    },
    change_planid(id) {
      this.$prompt('请输入推广账户id', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
        inputErrorMessage: '格式不正确'
      }).then(({value}) => {
        change_planid(id, value).then(response => {
          this.$message({
            type: 'success',
            message: response.msg
          })
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消绑定'
        })
      })
    },
    resetForm() {
      this.dialogFormVisible = false
    },
    resetTemp() {

    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}

.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
<style scoped>
.avatar {
  width: 200px;
  height: 200px;
  border-radius: 50%;
}
</style>
